﻿using Common.Communal;
using ERP.Domain.System;
using MediatR;
using System.Api.Read.Applications.Commands.Organizes;
using SqlSugar;
using System.DTO;
using AutoMapper;

namespace System.Api.Read.Applications.CommandHandlers.Organizes
{
    /// <summary>
    /// 组织机构查询命令处理程序
    /// </summary>
    public class OrganizeQueryCommandHandler : IRequestHandler<OrganizeQueryCommand, ApiResult<List<OrganizeDTO>>>
    {
        private readonly ISqlSugarClient _db;
        private readonly IMapper mapper;

        public OrganizeQueryCommandHandler(ISqlSugarClient db, IMapper mapper)
        {
            this._db = db;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理组织机构查询命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<ApiResult<List<OrganizeDTO>>> Handle(OrganizeQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<OrganizeDTO>>();
            var query = _db.Queryable<Organize>().LeftJoin<OrganizeType>((a, b) => a.OrganizeTypeNo == b.OrganizeTypeNo)
                .LeftJoin<User>((a, b, c) => a.UserNo == c.UserNo)
                .Where((a, b, c) => a.IsDeleted == false).Select((a, b, c) => new OrganizeDTO
                {
                    Id = a.Id,
                    OrganizeNo = a.OrganizeNo,
                    OrganizeName = a.OrganizeName,
                    OrganizeTypeNo = a.OrganizeTypeNo,
                    OrganizeTypeName = b.OrganizeTypeName,
                    ParentId = a.ParentId,
                    Level = a.Level,
                    UserNo = a.UserNo,
                    UserName = c.UserName,
                    IsDeleted = a.IsDeleted
                });
            // 根据组织名称或编号进行模糊查询
            if (!string.IsNullOrWhiteSpace(request.OrganizeNameNo))
            {
                query = query.Where(a => a.OrganizeName.Contains(request.OrganizeNameNo) || a.OrganizeNo.Contains(request.OrganizeNameNo));
            }

            // 根据组织类型进行精确查询
            if (!string.IsNullOrWhiteSpace(request.OrganizeTypeNo))
            {
                query = query.Where(a => a.OrganizeTypeNo == request.OrganizeTypeNo);
            }

            // 根据负责人用户编号进行精确查询
            if (!string.IsNullOrWhiteSpace(request.UserNo))
            {
                query = query.Where(a => a.UserNo == request.UserNo);
            }
            result.Code = EnumCode.Ok;
            result.Message = "组织机构查询成功";
            result.Data = query.ToList();
            return Task.FromResult(result);
        }
    }
}
